package com.handydata.antifraud.ws.dap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.common.exception.WsInvokeException;
import com.handydata.antifraud.to.dap.CisReportReqTO;
import com.handydata.antifraud.to.dap.CisReportResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.ws.WsInvocationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;


/**
 * 社保查询
 *
 */
@Slf4j
@Service("cisReportWsService")
@Comment("鹏元社保")
public class CisReportWsServiceImpl extends DataPlatformWsService<CisReportReqTO, CisReportResTO>
	implements WsInvocationService<CisReportReqTO, CisReportResTO> {

	@Override
	public CisReportResTO query(CisReportReqTO req)	throws WsInvokeException {
		log.info("鹏元社保请求参数 {}", req);
		CisReportResTO resTO = new CisReportResTO();
		if (StringUtils.isEmpty(req.getIdCard())) {
			log.error("鹏元社保参数校验 {}", "cid为空");
			resTO.setResCode("1111");
			resTO.setResMsg("鹏元社保接口cid参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getName())) {
			log.error("鹏元社保参数校验 {}", "name为空");
			resTO.setResCode("1111");
			resTO.setResMsg("鹏元社保接口name参数为空");
			return resTO;
		}
		this.dataType = DataSourceCode.CIS_REPORT.getCode();
		resTO = executeQuery(req);
		// 行内压测挡板处理
//		try {
//			Thread.sleep(590);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		resTO.setLastUnitName("测试公司");
//		resTO.setFactInsurePay(10000);
//		resTO.setCurrentStatus("1");
//		resTO.setUnitPersonCount(233);
//		resTO.setUnitType("1");
//		resTO.setHospitalCategory("test");
//		resTO.setEndowmentAmount(Double.valueOf("234"));
//		resTO.setTimesRecently24Months(123);
//		resTO.setTimesRecently60Months(123);
//		resTO.setSeriesTimesRecently60Months(123);
//		resTO.setInsuranceType("12");
//		resTO.setResCode("0000");
//		resTO.setResMsg("查询成功");
		return resTO;
	}
	
	@Override
	protected String createQueryXml(CisReportReqTO req) {
		StringBuilder xml = new StringBuilder();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
        xml.append("<subatm>");
        xml.append("<application>GwBiz.Req</application>");
        xml.append("<version>2.0.0</version>");
        xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
        xml.append("<transCode>300650</transCode>");
        xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
        xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
        xml.append("<name>").append(req.getName()).append("</name>");
        xml.append("<cid>").append(req.getIdCard()).append("</cid>");
        // 测试用户名和身份证号
//        xml.append("<name>").append("测试三").append("</name>");
//        xml.append("<cid>").append("110000199001031113").append("</cid>");
        xml.append("</subatm>");
        req.setQueryXml(xml.toString());
		return xml.toString();
	}
	
	@Override
	protected CisReportResTO parseResultAndSave(String resultXml, String orderId, Date createDate) {
		log.info("调用社保查询接口返回报文：{}", resultXml);
		CisReportResTO resTO = new CisReportResTO();
		try{
			// 解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if (null != jasonObject) {

				if ("0000".equals(jasonObject.getString("resCode"))) {
					JSONObject data = (JSONObject) jasonObject.get("returnValue");
					JSONArray jsar = (JSONArray)data.get("cisReport");
					JSONObject jsReport = jsar.getJSONObject(0);
					JSONObject socialInsurance= (JSONObject)jsReport.get("socialInsuranceOfShenzhen2");
					if("1".equals(socialInsurance.getString("treatResult"))) {
						JSONObject item= (JSONObject)socialInsurance.get("item");
						JSONObject baseInfo= (JSONObject)item.get("baseInfo");
						resTO.setLastUnitName(baseInfo.getString("lastUnitName"));
						resTO.setFactInsurePay(Integer.valueOf(baseInfo.getString("factInsurePay")));
						resTO.setCurrentStatus(baseInfo.getString("currentStatus"));
						resTO.setUnitPersonCount(Integer.valueOf(baseInfo.getString("unitPersonCount")));
						resTO.setUnitType(baseInfo.getString("unitType"));
						resTO.setHospitalCategory(baseInfo.getString("hospitalCategory"));
						resTO.setEndowmentAmount(Double.valueOf(baseInfo.getString("endowmentAmount")));
						JSONObject summaryInfo5Year= (JSONObject)item.get("summaryInfo5Year");
						resTO.setTimesRecently24Months(Integer.valueOf(summaryInfo5Year.getString("timesRecently24Months")));
						resTO.setTimesRecently60Months(Integer.valueOf(summaryInfo5Year.getString("timesRecently60Months")));
						resTO.setSeriesTimesRecently60Months(Integer.valueOf(summaryInfo5Year.getString("seriesTimesRecently60Months")));
						JSONObject historyInfo5Year = (JSONObject)item.get("historyInfo5Year");
						JSONArray historyList = (JSONArray)historyInfo5Year.get("items");
						JSONObject items = historyList.getJSONObject(0);
						resTO.setInsuranceType(items.getString("insuranceType"));
					}
				}	
				resTO.setResCode((String)jasonObject.get("resCode"));
				resTO.setResMsg((String)jasonObject.get("resMsg"));
				//resTO.setReqId(dataCallLogsReqBO.getId());
			} else {
				resTO.setResCode("1111");
				resTO.setResMsg("社保查询接口返回数据异常");
			}
		} catch (Exception e){
			log.info("调用社保查询接口返回报文解析异常：{}", e);
			resTO.setResCode("1111");
			resTO.setResMsg("调用社保查询接口返回报文解析异常");
		}
		log.info("调用社保查询接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}
	
	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, CisReportReqTO.class);
	}

}
